import { Descriptions, Drawer, Empty, message, Spin } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import useRequest from '@ahooksjs/use-request';
import MyIcon from '@/components/MyIcon';
import ScrollBarLayout from '@/components/ScrollBarLayout';

const DesItem = Descriptions.Item;

import detailStyle from '../../styles.less';
import { positionAPI } from '../../type';
import { requestFunCompon } from '@/utils';
import { TypographyTitle } from '@/components/Typography';
import { OtherDetailInfo } from './OtherDetailInfo';

export const DetailInfoPosDrawer = React.forwardRef(
  (
    {
      visible,
      resObj, //查询详情ID
      onCloseDra, //关闭弹框
    }: positionAPI.IDetailInfoPosType,
    ref,
  ) => {
    // 保存详情信息
    const [detailInfo, setDetailInfo] = useState<any>();
    const setDetail = useCallback(
      (obj: any) => {
        setDetailInfo(obj);
      },
      [detailInfo],
    );

    // 获取详情loading
    const [detailLoading, setDetailLoading] = useState<boolean>(true);
    const onInfoLoading = useCallback(() => {
      setDetailLoading(true);
    }, [detailLoading]);
    const closeInfoLoading = useCallback(() => {
      setDetailLoading(false);
    }, [detailLoading]);

    const [rouleInfo, setRouleInfo] = useState<any>([]); // 保存角色数据
    const [dutyInfo, setDutyInfo] = useState<any>([]); // 保存管辖数据
    const [subjectInfo, setSubjectInfo] = useState<any>([]); // 保存管辖数据
    const setRouDutySub = useCallback(
      (infoType: string, infoObj: any) => {
        // infoType  roule 为角色数据  duty 为管辖数据  subject 为科目数据
        if (infoType == 'roule') {
          setRouleInfo(infoObj);
        } else if (infoType == 'duty') {
          setDutyInfo(infoObj);
        } else if (infoType == 'subject') {
          setSubjectInfo(infoObj);
        }
      },
      [rouleInfo, dutyInfo, subjectInfo],
    );

    useEffect(() => {
      if (resObj && visible) {
        getDetailInfo?.run(resObj);
      }
      return () => {
        setDetail(null);
        onInfoLoading();
      };
    }, [resObj?.versionNum, visible]);

    // // 获取详情信息
    const getDetailInfo = useRequest(
      (infoID: any) => {
        let url = `/positionController/getPositionByID/${infoID?.id}`;
        return requestFunCompon('GET', url);
      },
      {
        manual: true,
        onSuccess: (res: any) => {
          if (res && res?.msgFlag) {
            message?.success(res?.msg);
            handleInfoSplit(res?.obj);
            setDetail(res?.obj);
          }
          closeInfoLoading();
        },
      },
    );

    // 处理详情信息,拆分出 科目 管辖, 角色数据
    const handleInfoSplit = (detailObj: any) => {
      let roleKey: any[] = detailObj.roleIds
        ? detailObj.roleIds.split(',')
        : []; //角色id
      let roleNameNodes: any[] = detailObj.roleNames
        ? detailObj.roleNames.split(',')
        : []; //角色名字

      let dutyScopeKey: any[] = detailObj.dutyScope
        ? detailObj.dutyScope.split(',')
        : []; //管辖 id
      let dutyScopeNameNodes: any[] = detailObj.dutyScopeName
        ? detailObj.dutyScopeName.split(',')
        : []; //管辖名字

      let msubJectList: any[] =
        detailObj?.msubjectList?.length > 0
          ? specialSubData(detailObj?.msubjectList, true, [])
          : [];

      if (detailObj?.roleIds) {
        let rouleList = specialSubData(roleKey, false, roleNameNodes);
        setRouDutySub('roule', rouleList);
      }
      if (detailObj?.dutyScope) {
        let dutyList = specialSubData(dutyScopeKey, false, dutyScopeNameNodes);
        setRouDutySub('duty', dutyList);
      }
      if (detailObj?.msubjectList?.length > 0) {
        setRouDutySub('subject', msubJectList);
      }
    };

    // 特殊处理数据
    const specialSubData = (keyList: any, intoType: boolean, rowList: any) => {
      let list: any[] = [];
      keyList?.forEach((item: any, index: number) => {
        if (intoType) {
          list?.push({ id: item?.subjectNum, name: item?.subjectName });
        } else {
          list?.push({ id: item, name: rowList[index] });
        }
      });
      return list;
    };

    return (
      <div>
        <Drawer
          open={visible}
          onClose={() => {
            onCloseDra();
          }}
          title={<div>岗位详情</div>}
          style={{ position: 'absolute' }}
          placement="right"
          getContainer={false}
          width={document.body.clientWidth * 0.35}
          headerStyle={{
            padding: '.5rem',
          }}
          bodyStyle={{
            padding: '0px 5px',
          }}
          closable={false}
          destroyOnClose={true}
        >
          <ScrollBarLayout>
            <div style={{ display: visible ? 'block' : 'none' }}>
              <Spin spinning={detailLoading}>
                <div style={{ padding: '10px' }}>
                  {detailInfo && detailInfo?.id ? (
                    <>
                      <div style={{ padding: '0px 0px 10px 0px' }}>
                        <TypographyTitle
                          level={4}
                          style={{
                            margin: 0,
                          }}
                        >
                          岗位信息
                        </TypographyTitle>
                      </div>
                      <div className={detailStyle['detailDept']}>
                        <Descriptions bordered={true} size="small" column={4}>
                          <DesItem
                            span={4}
                            label={
                              <span>
                                <MyIcon type="zuzhijigou" />
                                &nbsp;&nbsp;岗位名称
                              </span>
                            }
                          >
                            {(detailInfo && detailInfo.name) || '--'}
                          </DesItem>
                          <DesItem
                            span={4}
                            label={
                              <span>
                                <MyIcon type="zuzhijigou" />
                                &nbsp;&nbsp;岗位描述
                              </span>
                            }
                          >
                            {detailInfo && detailInfo?.description
                              ? detailInfo?.description
                              : '--'}
                          </DesItem>
                          <DesItem
                            span={2}
                            label={
                              <span>
                                <MyIcon type="zuzhijigou" />
                                &nbsp;&nbsp;所属部门
                              </span>
                            }
                          >
                            {detailInfo && detailInfo?.departmentName
                              ? detailInfo?.departmentName
                              : '--'}
                          </DesItem>
                          <DesItem
                            span={2}
                            label={
                              <span>
                                <MyIcon type="zuzhijigou" />
                                &nbsp;&nbsp;上级岗位
                              </span>
                            }
                          >
                            {detailInfo && detailInfo?.pName
                              ? detailInfo?.pName
                              : '--'}
                          </DesItem>
                          <DesItem
                            span={2}
                            label={
                              <span>
                                <MyIcon type="paixu" />
                                &nbsp;&nbsp;排序
                              </span>
                            }
                          >
                            <span>
                              {detailInfo && detailInfo?.seq
                                ? detailInfo?.seq
                                : '0'}
                            </span>
                          </DesItem>
                          <DesItem
                            span={2}
                            label={
                              <span>
                                <MyIcon type="zhuangtai" />
                                &nbsp;&nbsp;岗位状态
                              </span>
                            }
                          >
                            <span
                              style={{
                                color:
                                  detailInfo?.isOpen == 1 ? '#52c41a' : '#f00',
                              }}
                            >
                              {detailInfo && detailInfo.isOpen == 1
                                ? '启用'
                                : '禁用' || '--'}
                            </span>
                          </DesItem>
                          <DesItem
                            span={4}
                            label={
                              <span>
                                <MyIcon type="icon-beizhu" />
                                &nbsp;&nbsp;备注
                              </span>
                            }
                          >
                            {(detailInfo && detailInfo?.remark) || '--'}
                          </DesItem>
                        </Descriptions>
                      </div>

                      <OtherDetailInfo
                        infoType={'duty'}
                        dataList={dutyInfo}
                        titleIcon={
                          <MyIcon
                            type="zuzhijigou"
                            style={{ marginRight: 5 }}
                          />
                        }
                      />

                      <OtherDetailInfo
                        infoType={'roule'}
                        dataList={rouleInfo}
                        titleIcon={
                          <MyIcon type="user" style={{ marginRight: 5 }} />
                        }
                      />

                      <OtherDetailInfo
                        infoType={'subject'}
                        dataList={subjectInfo}
                        titleIcon={
                          <MyIcon type="shu" style={{ marginRight: 5 }} />
                        }
                      />
                    </>
                  ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  )}
                </div>
              </Spin>
            </div>
          </ScrollBarLayout>
        </Drawer>
      </div>
    );
  },
);
